package com.qyhl.module_home.new_message.detail;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_home.R;
import com.qyhl.module_home.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.config.MessageDetailBean;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

@Route(path = ARouterPathConstant.MESSAGE_DETAIL)
public class MessageDetailActivity extends BaseActivity implements MessageDetailContract.MessageDetailView {
    @BindView(R2.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R2.id.toolbar_layout)
    Toolbar toolbarLayout;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private MessageDetailPresenter mPresenter;

    private CommonAdapter commonAdapter;

    @Autowired(name = "type")
    String type;

    private String lastId = "0";

    private String userName;

    private List<MessageDetailBean> mDataList = new ArrayList<>();

    private String lastTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSupportActionBar(toolbarLayout);

    }


    @Override
    protected int getContentView() {
        return R.layout.home_activity_message_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        userName = CommonUtils.getInstance().getUserName();
        mPresenter = new MessageDetailPresenter(this);
        initView();
    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getMessageList(userName, lastTime + "", lastId, type);
    }


    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);
        loadMask.setEmptyImage(R.drawable.empty_message);
        switch (type) {
            case "system":
                toolbarTitle.setText("系统消息");
                lastTime = SpfManager.getInstance(this).getString("last_system_time", "0");
                break;
            case "tips":
                lastTime = SpfManager.getInstance(this).getString("last_tip_time", "0");
                toolbarTitle.setText("提示消息");
                break;
            default:
                toolbarTitle.setText("互动消息");
                break;
        }

        refreshLayout.setRefreshHeader(new MaterialHeader(this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        refreshLayout.setEnableLoadMore(true);

        recycleView.setLayoutManager(new LinearLayoutManager(this));

        recycleView.setAdapter(commonAdapter = new CommonAdapter<MessageDetailBean>(this, R.layout.home_item_message_detail, mDataList) {
            @Override
            protected void convert(ViewHolder holder, MessageDetailBean bean, int position) {
                TextView title = holder.getView(R.id.title);
                TextView content = holder.getView(R.id.content);
                TextView date = holder.getView(R.id.date);
                TextView detail = holder.getView(R.id.toDetail);
                RoundedImageView cover = holder.getView(R.id.cover);
                if (bean.getIsRead() == 1) {
                    title.setTextColor(getResources().getColor(R.color.global_black_lv0));
                } else {
                    title.setTextColor(getResources().getColor(R.color.global_black_lv4));
                }
                title.setText(bean.getTitle());

                date.setText(DateUtils.getMessageDateFormat(bean.getCreateTime()));

                content.setText(bean.getContent());

                if (StringUtils.isEmpty(bean.getImage())) {
                    cover.setVisibility(View.GONE);
                } else {
                    cover.setVisibility(View.VISIBLE);
                    Glide.with(MessageDetailActivity.this)
                            .load(bean.getImage())
                            .apply(new RequestOptions().error(R.drawable.cover_large_default).placeholder(R.drawable.cover_large_default))
                            .into(cover);
                }

                if (bean.getSkip() == 1) {
                    detail.setVisibility(View.VISIBLE);
                } else {
                    detail.setVisibility(View.GONE);
                }

            }
        });

    }

    private void setListeners() {
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                MessageDetailBean bean = mDataList.get(position);
                switch (bean.getContentType()) {
                    case "appTop":
                        break;
                    case "broke":
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getContentId()+"");
                        RouterManager.router(ARouterPathConstant.SCOOP_DETAIL_ACTIVIT,bundle);
                    }
                        break;
                    case "videoLive": {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getContentId()+"");
                        RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY,bundle);
                    }
                        break;
                    case "imageLive":{
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getContentId()+"");
                        RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY,bundle);
                    }
                        break;
                    case "circle":
                        {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", bean.getContentId()+"");
                            RouterManager.router(ARouterPathConstant.CIRCLE_DETAIL,bundle);
                        }
                        break;
                    case "integral":
                    {

                    }
                        break;
                    case "cmsCommonNews":
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getContentId()+"");
                        RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY,bundle);
                    }
                        break;
                    case "cmsVideoNews":
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getContentId()+"");
                        RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY,bundle);
                    }
                        break;
                    case "recNews":
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getContentId()+"");
                        RouterManager.router(ARouterPathConstant.NEWS_CATCH,bundle);
                    }
                        break;
                    case "link":
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getContentId()+"");
                        bundle.putString("title", bean.getTitle());
                        bundle.putString("url", bean.getLink());
                        RouterManager.router(ARouterPathConstant.ADV,bundle);
                    }
                        break;
                    case "activity":
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("actId", bean.getContentId()+"");
                        RouterManager.router(ARouterPathConstant.ACT_DETAILS,bundle);
                    }
                        break;
                    case "lottery":
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getContentId()+"");
                        bundle.putString("title", bean.getTitle());
                        RouterManager.router(ARouterPathConstant.LUCK_DRAW,bundle);
                    }
                        break;
                    default:
                    {
                        RouterManager.router(ARouterPathConstant.ACTIVITY_DEFAULT);
                    }
                            break;
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        loadMask.setOnReloadListener(v -> {
            lastId = "0";
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getMessageList(userName, lastTime + "", lastId, type);
        });

        refreshLayout.setOnLoadMoreListener(refreshLayout -> mPresenter.getMessageList(userName, lastTime + "", lastId, type));

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            lastId = "0";
            mPresenter.getMessageList(userName, lastTime + "", lastId, type);
        });
    }

    @Override
    public void setMessageList(List<MessageDetailBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refreshLayout.finishLoadMore();
        } else {
            refreshLayout.finishRefresh();
            mDataList.clear();
        }
        lastId = beanList.get(beanList.size() - 1).getId() + "";
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setNetError(String msg, boolean isMore) {
        if (isMore) {
            refreshLayout.finishLoadMore();
            showToast(msg, 4);
        } else {
            refreshLayout.finishRefresh();
            loadMask.setStatus(LoadingLayout.No_Network);
            loadMask.setReloadButtonText("点击重试~");
            loadMask.setNoNetworkText(msg);
        }
    }

    @Override
    public void setError(String msg, boolean isMore) {
        if (isMore) {
            refreshLayout.finishLoadMore();
            showToast(msg, 4);
        } else {
            refreshLayout.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            loadMask.setErrorText(msg);
        }
    }

    @Override
    public void setEmpty(String msg, boolean isMore) {
        if (isMore) {
            refreshLayout.finishLoadMore();
            Log.i("message", msg);
        } else {
            refreshLayout.finishRefresh();
            loadMask.setStatus(LoadingLayout.Empty);
            loadMask.setReloadButtonText("点击重试~");
            loadMask.setEmptyText(msg);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId()) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        switch (type) {
            case "system":
                SpfManager.getInstance(this).putString("last_system_time", DateUtils.getCurrentTime());
                BusFactory.getBus().post(new Event.MessageRefresh("system"));
                break;
            case "tips":
                SpfManager.getInstance(this).putString("last_tip_time", DateUtils.getCurrentTime());
                BusFactory.getBus().post(new Event.MessageRefresh("tip"));
                break;
            default:
                toolbarTitle.setText("互动消息");
                break;
        }
    }



}
